package com.yuncheng.spcyApi.gxca;    //构造广西ca签章接口需要的json

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.ca.GxCaConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxWjjl;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcySqsxWjjlService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.Util;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;

@Component(value = "gxcaService2")
public class gxcaService{
	private static final Logger log = LoggerFactory.getLogger(gxcaService.class);

	@Resource
	private BusinessConstant businessConstant;

	@Resource
	@Lazy
	private ISpcySqsxWjjlService spcySqsxWjjlService;

//	public static String appKey = "yjjrs";
//	public static String appKey = "gxyjj";

//	public static String appSecret = "z2uRgjxqRSA2qF2kGZ65iwTeyBh76yJy2e9Xfw==";  // 正式
//	public static String appSecret = "LI0OEcXDrHsjaj987qsStflM7cr7kNXoddSGjQ==";
//	public static String appSecret = "lYjPTq/4ZQntPgFDPDDssERNQX605BvG2hy3Yw=="; // 内网

//	public static String getSealListUrl = "https://172.18.0.100/yjjcaess/gxyjj/getSealList"; // 正式
//	public static String getSealListUrl = "http://114.115.181.136:9232/yjjcaess/gxyjj/getSealList";
//	public static String getSealListUrl = "http://172.18.0.11:8080/yjjcaess/gxyjj/getSealList"; // 内网

	public static String fjpathv = "";

	public static String fjpathr = "";

	public String createJSONdata(SpcySqsxWjjl wjjl,
								 String certSn,
								 List<String> sealList,
								 HashMap<String, Object> buffer)throws Exception{
		String appKey = GxCaConstant.appKey;
		String timeStamp=new Date().getTime()+"";
		String nonce="nonce1234";

//		String basePath = "http://172.18.0.104:" + req.getServerPort() + path;
//		StringBuffer baseUrl = new StringBuffer(this.baseUrl);
		StringBuffer baseUrl = new StringBuffer(GxCaConstant.System_Http_Url_Base);
//		StringBuffer baseUrl = new StringBuffer("https://bg.yjj.gxzf.gov.cn");
//		baseUrl.append("/t_yjjspzx-svc");
		baseUrl.append("/api/spzx-spcy/spcySqsxWjjl");
		baseUrl.append("/getCrossLocalFile");
		baseUrl.append("?").append("id").append("=").append(wjjl.getId());

//		String pdfUrl = basePath + "/ypcygl!downloadDzbg.do?ids=" + cybasic.getFsid();
		String pdfUrl = baseUrl.toString();  // 下载文件http路径
//		pdfUrl = "http://113.16.217.137:45673/uploadfiles//%E6%A0%87%E5%87%86%E7%AE%A1%E7%90%86%E9%99%84%E4%BB%B6//%E2%9E%A4%E5%8C%BB%E7%96%97%E5%99%A8%E6%A2%B0%E6%A0%87%E5%87%86//1234.pdf";

//		String realpath = cybasic.getLccb_dzbgurl().replaceAll(OfficeConfig.get("fjpathv"),OfficeConfig.get("fjpathr"));
		String realpath = businessConstant.YUNCEHNG_PATH_UPLOAD + wjjl.getFcflj(); // 文件存放的路径
//		String realpath = "/home/yjjapp/upFiles/wjjl" + wjjl.getFcflj(); // 文件存放的路径
//		realpath = "D:/upFiles2/1234.pdf";

//		int lccb_ymzs = Integer.parseInt(cybasic.getLccb_ymzs())+2;
		int lccb_ymzs = 2; // 页数
		// 创建骑缝章第六个参数
		String qfzcs6 = "";
		for(int i = 1; i < lccb_ymzs; i++){
			qfzcs6 += i + ",";
		}
		String ruleInfo_qfz="0,25000,5,3,50,"+qfzcs6;//骑缝章
		String ruleInfo_sy="AUTO_ADD:0,-1,0,0,255,syyz)|(4,";//首页章
		String ruleInfo_CMA="AUTO_ADD:0,-1,0,0,255,cmayz)|(4,";//cma章
		String ruleInfo_CNAS="AUTO_ADD:0,-1,0,0,255,cnasyz)|(4,";//cnas章
		String ruleInfo_sqqzr="AUTO_ADD:0,-1,0,0,255,sqqzr)|(4,";//签名

		String seal="";
		if(!Util.isEmpty(buffer.get("seal").toString())){
			seal = buffer.get("seal").toString();
		}

		String CMA_flag="";
		if(!Util.isEmpty(buffer.get("CMA_flag"))){
			CMA_flag = buffer.get("CMA_flag").toString();
		}

		String CNAS_flag="";
		if(!Util.isEmpty(buffer.get("CNAS_flag"))){
			CNAS_flag=buffer.get("CNAS_flag").toString();
		}

		String signNode = "";

		for(String sealName : sealList){
			if(seal.equals(sealName) || (seal=="" && sealName.contains("检验报告专用章"))){
		/*		signNode += (signNode == "" ? "" : ",");
				signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_qfz+"\"}";
				signNode += ",{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sy+"\"}";*/

				if (StringUtils.isNotBlank(buffer.get("QFZ").toString()) && buffer.get("QFZ").toString().equals("true")) {
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\"" + sealName + "\",\"ruleInfo\":\"" + ruleInfo_qfz + "\"}";
				}

				if (StringUtils.isNotBlank(buffer.get("SYZ").toString()) && buffer.get("SYZ").toString().equals("true")){
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sy+"\"}";
				}

			}
			if(sealName.contains("CMA") && CMA_flag.equals("true")){
				signNode += (signNode == "" ? "" : ",");
				signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_CMA+"\"}";
			}
			if(sealName.contains("CNAS") && CNAS_flag.equals("true")){
				signNode += (signNode == "" ? "" : ",");
				signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_CNAS+"\"}";
			}
			if(sealName.contains("个人章")){
				/*signNode += (signNode == "" ? "" : ",");
				signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sqqzr+"\"}";*/
				if (StringUtils.isNotBlank(buffer.get("SQQZR").toString()) && buffer.get("SQQZR").toString().equals("true")) {
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sqqzr+"\"}";
				}
			}

			//测试用
			if(seal.equals(sealName) && seal.contains("测试")){
				/*signNode += (signNode == "" ? "" : ",");
				signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_qfz+"\"}";
				signNode += ",{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sy+"\"}";*/

				if (StringUtils.isNotBlank(buffer.get("QFZ").toString()) && buffer.get("QFZ").toString().equals("true")) {
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\"" + sealName + "\",\"ruleInfo\":\"" + ruleInfo_qfz + "\"}";
				}

				if (StringUtils.isNotBlank(buffer.get("SYZ").toString()) && buffer.get("SYZ").toString().equals("true")){
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_sy+"\"}";
				}

				if(CMA_flag.equals("true")){
					signNode += (signNode == "" ? "" : ",");
					signNode += "{\"sealName\":\""+sealName+"\",\"ruleInfo\":\""+ruleInfo_CMA+"\"}";
				}
			}
		}


		String json_data="{";
		//<!-- 保存的文件名 -->
		json_data += "\"fileNo\":\""+wjjl.getFwjccmc()+"\",";
//		json_data += "\"fileNo\":\""+"1234.pdf"+"\",";
		json_data += "\"appKey\":\""+appKey+"\",";
		json_data += "\"nonce\":\""+nonce+"\",";
		json_data += "\"timeStamp\":\""+timeStamp+"\",";
		json_data += "\"signature\":\""+getMD5(nonce,timeStamp)+"\",";
		json_data += "\"signNode\":["+signNode+"],";
		json_data += "\"fileType\":\"pdf\",";
		json_data += "\"source\":\"1\",";
		json_data += "\"fileData\":\""+pdfUrl+"\",";
		json_data += "\"sm3Data\":\""+new GetFileSM3Helper().getFileSM3Hash(realpath)+"\",";
		json_data += "\"retureType\":\"1\",";
		json_data += "\"certSn\":\""+certSn+"\"";

		json_data+="}";
		return json_data;
	}

	public String getMD5(String nonce,String timeStamp)throws Exception{
		String appSecret = GxCaConstant.appSecret;
		String md5 = DigestUtils.md5Hex(appSecret+nonce+timeStamp);
		return md5;
	}

	// 报告签章
	public com.alibaba.fastjson.JSONObject dzbgQz(String url,String json){
			com.alibaba.fastjson.JSONObject jsonObject=new com.alibaba.fastjson.JSONObject();
			try{
				//CloseableHttpClient httpClient = (CloseableHttpClient)SkipHttpsUtil.wrapClient();
				HttpPost httpPost=new HttpPost(url);
				httpPost.setHeader("content-type","application/json;charset=utf-8");
				httpPost.setHeader("Accept","application/json");
				//信任所有证书，关闭主机名校验
				SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
				SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
				NoopHostnameVerifier.INSTANCE);
				// 创建Httpclient对象
				CloseableHttpClient httpClient= HttpClients.custom().setSSLSocketFactory(sslsf).build();


				//请求参数转JOSN字符串
				StringEntity stringEntity=new StringEntity(json, Charset.forName("UTF-8"));
				stringEntity.setContentType("application/json");
				httpPost.setEntity(stringEntity);

				HttpResponse response=httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200){
				jsonObject= JSON.parseObject(EntityUtils.toString(response.getEntity(),"UTF-8"));
			}else{
//				throw new Exception("错误代码："+response.getStatusLine().getStatusCode());
				log.error("错误代码: {}",response.getStatusLine().getStatusCode());
				throw new BusinessException("错误代码："+response.getStatusLine().getStatusCode());
			}

			}catch(Exception e){
				log.error("报告签字出错：{}", e.getMessage());
			}
			return jsonObject;
	}

	// 下载已签章的电子报告到附件库
	public JSONObject downloadDzbgQz(String downloadurl, String ids, JSONObject object){
		SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(ids);
		// 判断是否已经盖章
		if (StringUtils.isNotBlank(wjjl.getFgzzt()) && wjjl.getFgzzt().equals(SpcyConstant.WJJL_ZT_GZ)){
//			object.put("message", "已经盖章");
//			object.put("code", "4001");
			return object;
		}
		String oldCflj = wjjl.getFcflj();

		String pdfname = GetUuIdUtils.NotReplaceUuId() + ".pdf"; // 文件名称

		try{
			HttpGet httpget=new HttpGet(downloadurl);
			// 加入Referer,防止防盗链
			httpget.setHeader("Referer",downloadurl);
			SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
			SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
			NoopHostnameVerifier.INSTANCE);
			// 创建Httpclient对象
			CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

			HttpResponse response=httpClient.execute(httpget);
			HttpEntity entity=response.getEntity();
			InputStream is=entity.getContent();

			String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
			String newDir = "/"+nowDay;

			String realurl = businessConstant.YUNCEHNG_PATH_UPLOAD+newDir;
			File newDirUrl = new File(realurl);
			if (!newDirUrl.exists()){
				newDirUrl.mkdirs();
			}

			FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
			byte[]buffer = new byte[1024*10];
			int ch = 0;
			while((ch = is.read(buffer)) != -1){
				fileout.write(buffer,0,ch);
			}
			is.close();
			fileout.flush();
			fileout.close();

			wjjl.setFcflj(newDir + "/" + pdfname);
			wjjl.setFwjccmc(pdfname);
//			wjjl.setFwjlx(".pdf");
//			wjjl.setFjdcflj(oldCflj);
			wjjl.setFgzzt("是");
			spcySqsxWjjlService.updateById(wjjl);

		}catch(Exception e){
			log.error("出错：{}", e.getMessage());
		}
		return object;
	}

	//获取印章名列表
	public List getSealList(String certSn) throws Exception{
		String url = GxCaConstant.getSealListUrl;
		//定义接收数据
		List<String> sealList = new ArrayList<>();
		JSONObject json = new JSONObject();
		json.put("certSn", certSn);
		String jsonStr = json.toString();
		com.alibaba.fastjson.JSONObject jsonObject = httpGet(url, jsonStr);


		if (jsonObject.containsKey("data")) {
			List<Map<String, String>> list = (List<Map<String, String>>) jsonObject.get("data");

			for (Map<String, String> map : list) {
				sealList.add(map.get("sealName"));
			}
			//object.put("sealList", sealList);
		}else {
			//object.put("state", 0);
			//object.put("msg", jsonObject.get("message"));
			log.error("错误：{}",jsonObject.get("message").toString());
			throw new BusinessException(jsonObject.get("message").toString());
		}
		return sealList;
	}

	public com.alibaba.fastjson.JSONObject httpGet(String url, String json){
		com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
		try {

			/*BaseHttpMethod.HttpGetWithEntity httpGet = new BaseHttpMethod.HttpGetWithEntity(url);
			httpGet.setHeader("content-type","application/json;charset=utf-8");*/

			//信任所有证书，关闭主机名校验
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
					SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
					NoopHostnameVerifier.INSTANCE);
			// 创建Httpclient对象
			CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

			//请求参数转JOSN字符串
			StringEntity stringEntity = new StringEntity(json, Charset.forName("UTF-8"));
			stringEntity.setContentType("application/json");
//			httpGet.setEntity(stringEntity);

//			CloseableHttpResponse response = httpClient.execute(httpGet);
			CloseableHttpResponse response = httpClient.execute(null);

			if(response.getStatusLine().getStatusCode()==200){
				jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
			}else {
				log.error("错误代码：{}",response.getStatusLine().getStatusCode());
				throw new BusinessException("错误代码：" + response.getStatusLine().getStatusCode());
			}

			log.info("jsonObject: {}", jsonObject);
		} catch (Exception e) {
			log.error("httpGet出错：",e.getMessage());
		}
		return jsonObject;
	}
}
